# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA is None or headB is None:
            return None
        tail = headA
        #  用来记录A的尾
        while tail.next is not None:
            tail = tail.next
        tail.next = headB
        #  链接两个链表 如果交叉 那么一定有环
        fast = headA
        slow = headA
        while fast.next is not None and fast.next.next is not None:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                break
        if fast.next is None or fast.next.next is None:
            tail.next = None
            return None
        slow = headA
        while slow != fast:
            slow = slow.next
            fast = fast.next
        tail.next = None
        return slow
